package com.cskaoyan.order.mq;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;

/**
 * @author raccoon@littleraccoon.xyz
 * @since 2022/12/06 15:39
 */
@Component
@Slf4j
public class DelayOrderCancelProducer {

    DefaultMQProducer defaultMQProducer;

    // private static final Logger log = LoggerFactory.getLogger(DelayOrderCancelProducer.class);

    @PostConstruct
    public void start() {
        defaultMQProducer = new DefaultMQProducer("delay_order_cancel_producer");
        defaultMQProducer.setNamesrvAddr("127.0.0.1:9876");
        try {
            defaultMQProducer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    /**
     * send a delay message which contains orderId for a successful order
     *
     * @param orderId
     * @return boolean
     * @author raccoon@littleraccoon.xyz
     * @since 2022/12/06 15:42
     */
    public boolean sendOrderCancelMessage(String orderId) {
        log.debug("slf4j print debug msg:{}", "start sending a message");
        Message message = new Message("delay_order_cancel", orderId.getBytes(StandardCharsets.UTF_8));
        // message.setDelayTimeLevel(3);
        message.setDelayTimeLevel(18);
        SendResult sendResult;
        try {
            sendResult = defaultMQProducer.send(message);
        } catch (MQClientException | RemotingException | MQBrokerException | InterruptedException e) {
            e.printStackTrace();
            return false;
        }
        return sendResult != null && SendStatus.SEND_OK.equals(sendResult.getSendStatus());
    }
}
